package com.splunk.hiring.imov.persist.db.impl;

import java.util.List;

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.splunk.hiring.imov.entity.Movie;
import com.splunk.hiring.imov.persist.db.MovieDao;
import com.splunk.hiring.imov.utils.PagedData;
import com.splunk.hiring.imov.utils.PagedData.Pager;

@Repository
@Transactional
public class MovieDaoImpl extends AbstractDaoImpl implements MovieDao{

	@Override
	public PagedData<Movie> getPagedMovies(Pager pager) {
		String hql = "from Movie m where m.movieInfo.rateCount>20 order by m.movieInfo.averageRate desc";
		Query query = this.getCurrentSession().createQuery(hql);
		query.setFirstResult(pager.getStart());
		query.setMaxResults(pager.getPageSize());
		List<Movie> movies = query.list();
		return new PagedData<Movie>(pager,movies);
	}

	@Override
	public Long getTmdbIdByMovie(Movie movie) {
		return (Long)this.getHibernateTemplate().find("select tmdbId from Link l where l.movie=?", movie).get(0);
	}

	@Override
	public Movie getMovieById(Long movieId) {
		return this.getHibernateTemplate().get(Movie.class,movieId);
	}

	@Override
	public PagedData<Movie> getPagedMoviesWithYearsAndGenres(String years,String genres,Pager pager) {
		Criteria criteria = this.getCurrentSession().createCriteria(Movie.class);
		if(StringUtils.isNotEmpty(years)){
			String[] year = years.split("-");
			criteria.add(Restrictions.between("year", Integer.parseInt(year[0]), Integer.parseInt(year[1])));
		}
		if(StringUtils.isNotEmpty(genres)){
			criteria.add(Restrictions.ilike("genres", "%"+genres+"%"));
		}
		criteria.addOrder(Order.desc("movieInfo.averageRate"));
		criteria.add(Restrictions.gt("movieInfo.rateCount", new Integer(20)));
		criteria.setFirstResult(pager.getStart());
		criteria.setMaxResults(pager.getPageSize());
		List<Movie> results = criteria.list();
		return new PagedData<Movie>(pager,results);
	}

	@Override
	public PagedData<Movie> getPagedMoviesByName(String shortName,Pager pager) {
		String hql = "from Movie m where m.title like :mtitle and m.movieInfo.rateCount>20 order by m.movieInfo.averageRate desc";
		Query query = this.getCurrentSession().createQuery(hql);
		query.setString("mtitle", "%"+shortName+"%");
		query.setFirstResult(pager.getStart());
		query.setMaxResults(pager.getPageSize());
		List<Movie> movies = query.list();
		return new PagedData<Movie>(pager,movies);
	}

}
